#include "m0wig.h"
#include "ui_m0wig.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>

M0Wig::M0Wig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::M0Wig)
{
    ui->setupUi(this);
    ui->comboBox->setStyleSheet("QComboBox { background-color: rgba(50, 50, 50, 150);color: white;border: 1px solid gray;}");
    ui->refresh_button->setStyleSheet("QPushButton {background: transparent;background-color: rgba(255, 255, 255, 50); color: white;}");

    connect(ui->comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(onComboBoxChanged(int)));
}

M0Wig::~M0Wig()
{
    delete ui;
}

void M0Wig::mqttRecv(const QByteArray &msg)
{
    qDebug()<< "mqttRecv:" << endl << msg;

    QJsonDocument doc = QJsonDocument::fromJson(msg);

    QJsonObject obj = doc.object();

    double temp = obj["TEM"].toDouble();
//    qDebug() << temp << endl;
    ui->temp_lcd->display(temp);



    double hum = obj["HUM"].toDouble();
//    qDebug() << hum << endl;
    ui->hum_lcd->display(hum);


    QString led = obj["LED"].toString();

    QString fan = obj["FAN"].toString();

    QString fmq = obj["VOICE"].toString();

    QString light = obj["LIGHT"].toString();

    emit modSignal(led,fan,fmq,light);

    if(temp >= 30)
    {
        emit TemSignal("on","on");
    }


}

void M0Wig::onComboBoxChanged(int index)
{
    QMQTT::Message msg;
    msg.setTopic(TOPIC_CTL_DOWN);
    QByteArray payload;

    switch(index)
    {
        case 0:
            qDebug() << "循环" << endl;
            payload = "{\"MODE\":1}";
            msg.setPayload(payload);
            GlobalVal::mqtt->publish(msg);
            break;
        case 1:
            qDebug() << "对比" << endl;
            payload = "{\"MODE\":2}";
            msg.setPayload(payload);
            GlobalVal::mqtt->publish(msg);
            break;
        case 2:
            qDebug() << "刷新" << endl;
            payload = "{\"MODE\":3}";
            msg.setPayload(payload);
            GlobalVal::mqtt->publish(msg);
            break;
        default:
            qDebug() << "未知" <<endl;
            break;
    }
}

void M0Wig::on_refresh_button_clicked()
{
    QMQTT::Message msg;
    msg.setTopic(TOPIC_CTL_DOWN);

    QByteArray payload = "{\"COM\":1}";
    msg.setPayload(payload);
    GlobalVal::mqtt->publish(msg);
}
